import axios from 'axios'
import Config from './Config'
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
export  default  class Http {
  constructor (){

  }
  static toType(obj){
    return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
  }
  static filterNull(o){
    for (let i in o) {
      if (o[i] === null || o[i] === undefined || o[i] === '') {
        delete o[i]
      }
      if (this.toType(o[i]) === 'string') {
        o[i] = o[i].trim()
      } else if (this.toType(o[i]) === 'object') {
        o[i] =this.filterNull(o[i])
      } else if (this.toType(o[i]) === 'array') {
        o[i] = this.filterNull(o[i])
      }
    }
    return o
  }
  static setFormData (params) {
    let formData = new FormData();
    if (typeof (params) === 'array') {
      for (let i in params) {
        if (typeof(params[i]) === 'object') {
          for (let j in params[i]) {
            formData.append(j, params[i][j]);
          }
        }
      }
      params = formData;
    } else if (typeof(params) === 'object') {
      for (let i in params) {
        formData.append(i, params[i]);
      }
      params = formData;
    }
    return params
  }
  static request (params) {
    let _this = this;
    params.data = this.filterNull(params.data);
    return new Promise((resolve, reject) => {
      let _before = '';
      let _finally = '';
      let _error = '';
      let _beforeSuccess = '';
      if (params._before && params._before !== null) {
        _before = params._before
      }
      if (params._finally && params._finally !== null) {
        _finally = params._finally
      }
      if (params._beforeSuccess && params._beforeSuccess !== null) {
        _beforeSuccess = params._beforeSuccess
      }
      if (params._error && params._error !== null) {
        _error = params._error
      }
      if (typeof _before === 'function') {
        _before()
      }
     params.data =_this.setFormData(params.data);
      axios({
        method: params.method || 'GET',
        url: params.url,
        data:params.data,
        baseURL: Config.chatUrl,
        withCredentials: false,
        timeout: 20000,
      }).then(function (res) {
        if (typeof _beforeSuccess === 'function') {
          _beforeSuccess(res.data.data)
        }
        if (res.data.code == 200) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
        if (typeof _finally === 'function') {
          _finally()
        }
      }).catch(function (err) {

      })

    })
  }
}
